package org.example.myleet.rosalind.lexv;

import java.io.*;

public class Solution {
    public static void main(String[] args) throws IOException {
        Solution solution = new Solution();
//        String alphabetInput = "D N A";
        String alphabetInput = "H Z K A W E Y F L C";
        int n = 3;
        String[] alphabetStrings = alphabetInput.split(" ");
        char[] alphabets = new char[alphabetStrings.length];
        for (int i = 0; i < alphabetStrings.length; ++i) {
            alphabets[i] = alphabetStrings[i].charAt(0);
        }
        String path = solution.getClass().getResource("").getPath();
        path += "output.txt";
        File outputFile = new File(path);
        if (outputFile.exists()) {
            outputFile.delete();
        }
        outputFile.createNewFile();
        OutputStream os = new FileOutputStream(outputFile);
        solution.outputAllCombinations(alphabets, n, os);
    }

    public void outputAllCombinations(char[] alphabet, int n, OutputStream os) throws IOException {
        backtrack(alphabet, new StringBuilder(), n, os);
    }

    private void backtrack(char[] alphabet, StringBuilder sb, int n, OutputStream os) throws IOException {
        if (0 < sb.length()) {
            os.write(sb.toString().getBytes());
            os.write("\n".getBytes());
        }
        if (sb.length() == n) {
            return;
        }
        for (int i = 0; i < alphabet.length; ++i) {
            sb.append(alphabet[i]);
            backtrack(alphabet, sb, n, os);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
